<template>
  <!--{{router.currentRoute.value.query}}-->
  <div class="mobile-container">
    <van-skeleton title :row="3" :loading="loading.value">
      <template v-for="(item,index) in obj.value">
        <template v-if="item.exit">
         <van-cell-group>
           <van-cell>
             <template v-if="item.type=='date'">
               <van-datetime-picker
                   v-model="item.value"
                   type="datetime"
                   :title="item.title"
                   :min-date="mindate"
                   :max-date="maxdate"
               />
             </template>
             <template v-if="item.type=='text'">
               <van-field :label="item.title" autosize v-model="item.value" type="textarea" placeholder="请输入文本内容"/>
             </template>
             <template v-if="item.type=='number'">
               <van-field v-model="item.value" type="number" :label="item.title"/>
             </template>
           </van-cell>
         </van-cell-group>
        </template>
      </template>
     <van-cell>
       <van-button size="large" @click="submitData">提交</van-button>
     </van-cell>

    </van-skeleton>
  </div>
</template>

<script lang="ts">
import {useRouter} from "vue-router";
import {Schema} from "../../../lib/schemaType"
import {reactive, Ref} from "vue";
import {uiType} from "@/lib/uiInterface";
import {Notify} from "vant";
import statusTree from "@/views/mobile/form/mobile_status_tree.vue"
export default {
  name: "mobile_form",
  setup() {
    const debug = true;
    const state = reactive({
      status_id:1
    })
    const router = useRouter();
    const loading = reactive({value: true})
    const resultObj = reactive({value: {} as Schema})
    const obj = reactive({value: [] as uiType[]})
    const mindate=new Date(1900,0,0);
    const maxdate=new Date(2100,0,0);
    const formid = reactive({value:0});
    const title = reactive({
      value: ''
    })
    const types = reactive([
      {
        id: 0,
        name: 'date',
        description: '日期',
        isUse: true,
      },
      {
        id: 1,
        name: 'text',
        description: '文本',
        isUse: true,
      },
      {
        id: 2,
        name: 'number',
        description: '数字',
        isUse: true,
      },
      {
        id: 3,
        name: 'radio',
        description: '暂时没用到的复选框',
        isUse: false,
      },
      {
        id: 4,
        name: 'array',
        description: '数组',
        isUse: false,
      }
    ])
    // console.log(router.currentRoute.value.query)
    if (
        (!!router.currentRoute.value.query.type) && (!!router.currentRoute.value.query.clubid) ||
        (!!router.currentRoute.value.query.type) && (!!router.currentRoute.value.query.formid)
    ) {
      if (router.currentRoute.value.query.type == 'new') {
        fetch("api/club/" + router.currentRoute.value.query.clubid + "/form/join")
            .then(
                res => {
                  // console.log(res)
                  if (res.status != 200) {
                    throw "网络错误"
                  } else {
                    return res.json();
                  }
                }
            ).then(
            json => {
              // console.log(json)
              formid.value = json.id;
              title.value = json.title;
              resultObj.value = json.value as Schema;
              // 解析接收到的schame
              doAnalysis(resultObj);
              loading.value = false;
            }
        ).catch(e=>{
          Notify("网络错误");
          setTimeout(()=>{router.push({path:'/owner'});},3000);
        })
      } else if (
          router.currentRoute.value.query.type == 'public'
      ) {
        fetch("api/form/" + router.currentRoute.value.query.formid)
            .then(
                res => {
                  // console.log(res)
                  if (res.status == 200 ) {
                    return res.json();
                  }
                  else if( res.status == 500 ){
                    // console.log(res)
                    throw "网络错误"
                  }

                  else {
                    // console.log(res)
                    throw "网络错误"
                  }
                }
            )
            .then(
                json => {
                  // console.log(json)
                  if(!!json.error){
                    throw "你不是该社团的成员";
                  }
                  formid.value = json.id;
                  title.value = json.title;
                  resultObj.value = json.value as Schema;
                  // 解析接收到的schame
                  doAnalysis(resultObj);
                  loading.value = false;
                }
            )
            .catch(e=>{
              Notify(e);
              setTimeout(()=>{router.push({path:'/owner'});},3000);

            })
      }
    }
    if(
        !!router.currentRoute.value.params.data &&
        !!router.currentRoute.value.params.formid &&
        !!router.currentRoute.value.params.applyid
    ){
      // console.log(111)
      fetch("api/form/" + router.currentRoute.value.params.formid)
          .then(
              res => {
                // console.log(res)
                if (res.status != 200 && res.status != 500) {
                  // console.log(res)
                  throw "网络错误"
                } else {
                  return res.json();
                }
              }
          )
          .then(
              json => {
                // console.log(json)
                if(!!json.error){
                  throw "你不是该社团的成员";
                }
                formid.value = json.id;
                title.value = json.title;
                resultObj.value = json.value as Schema;
                let tdata = JSON.parse(router.currentRoute.value.params.data.toString());
                // console.log(tdata)
                // 解析接收到的schame
                doAnalysis(resultObj);
                obj.value.forEach(item=>{
                  if (debug){
                    console.log("item:")
                    console.log(item)
                  }
                  if( (item.type+item.id) in tdata){

                    if(item.type == 'date'){
                      item.value = new Date(tdata[item.type+item.id]);
                    }else{
                      item.value = tdata[item.type+item.id]
                    }
                  }
                })
                loading.value = false;
              }
          )
          .catch(e=>{
            Notify(e);
            setTimeout(()=>{router.push({path:'/owner'});},3000);

          })
    }
    const doAnalysis = function (resultObj: { value: Schema } ) {
      if (resultObj.value.type == "object") {
         // console.log(JSON.stringify(resultObj))
        for (var i in resultObj.value.properties) {
          // console.log(i,":",resultObj.value.properties[i])
          let t = resultObj.value.properties[i];
          let tobj: uiType = {
            type: 'text',
            type_id: 1,
            value: null,
            id: -1,
            exit: true,
            title: "",
            required: '2',
          }
          // console.log(t.title)
          tobj.title = t.title as string;
          if (t.type == "string") {
            if (!!t.format) {
              if (t.format == 'date') {
                tobj.type = 'date';
                tobj.type_id = 0;
                tobj.value=new Date();
              } else {
                tobj.type = 'text';
                tobj.type_id = 1;
                tobj.value = "";
              }
            }
          } else if (t.type == 'number') {
            tobj.type = 'number';
            tobj.type_id = 2;
            tobj.value = 0;
          }
          tobj.exit = true;
          let tt = "string1"
          tobj.id = ((i: string): number => {
            const res = /.*?(\d+)/.exec(i)
            if (!res) {
              //
              //
              return 0
            }
            return parseInt(res[1])
          })(i)
          obj.value.push(tobj);
        }
        if (!!resultObj.value.required) {
          resultObj.value.required.forEach(e => {
            obj.value.forEach(e2 => {
              if (e == e2.type + e2.id) {
                e2.required = '1';
              }
            })
          })
        }
        // console.log(JSON.stringify(obj.value))
      }
    }
    let submitData_clicked:boolean = true;
    const submitData = function (){
      if(submitData_clicked ){
        // console.log("dianjile")
        let tempobj : any = {};
        obj.value.forEach(item=>{
          if(item.type=='date'){
            tempobj[item.type+item.id] = (item.value as Date).toISOString();
          }
          tempobj[item.type+item.id] = item.value;
        })
        // console.log(tempobj)
        if( !! router.currentRoute.value.query.type ){
          fetch("api/form/"+formid.value,{
            method:"POST",
            headers:{
              'content-type':'application/json'
            },
            body:JSON.stringify({content:tempobj})
          }).then(res=>{
            if(res.status == 200 ){
              return res.json();
            }else {
              return res.json();
              // console.log(res)
              // throw "网络错误"
            }
          }).then(json=>{
            // console.log(json)
          }).catch(e=>{Notify(e)})
        }else if( !! router.currentRoute.value.params.formid){
          fetch("api/user/self/application/single/"+router.currentRoute.value.params.applyid,{
            method:"POST",
            headers:{
              'content-type':'application/json'
            },
            body:JSON.stringify({content:tempobj})
          }).then(res=>{
            if(res.status == 200 ){
              return res.json();
            }
            else if ( res.status == 204 ){
              router.push({
                path:"/formview",
                query:{
                  formid: router.currentRoute.value.params.formid,
                  applyid:router.currentRoute.value.params.applyid,
                }
              });
            }
            else {
              // console.log(res)
              // throw "网络错误"
              return res.json();
            }
          }).then(json=>{
            // console.log(json)
          }).catch(e=>{Notify(e)})

        }

        // console.log(formid.value)
        submitData_clicked = false;
      }else {
        Notify("提交中 请不要重复点击")
      }
      ;
    }
    return {
      router, loading, obj,submitData,mindate,maxdate
    }
  },
  components:{
    statusTree
  }
}
</script>

<style scoped>
.mobile-container {
  padding-top: 30px;
  padding-bottom: 200px;
}
</style>